package com.example.music;


import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.util.Timer;
import java.util.TimerTask;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textView;
    private Button button_start;
    private Button button_pause;
    private Button button_stop;
    private Button button_exit;


    Intent intent = null;
    MyConn conn = new MyConn();

    MusicService musicService;

    ///*  //method1
    private SeekBar seekbar;
    private Timer timer;//定时器
    private boolean isSeekbarChaning;//互斥变量，防止进度条和定时器冲突。
    // */
    private TextView tv_start;
    private TextView tv_end;
    //comple


    //method2
    private int time;
    Handler handler=new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //System.out.println("接收时间");
            //tv_show.setText("计时时间："+msg.arg1);
            if(msg.arg1>0){
                if (!isSeekbarChaning) {
                    seekbar.setProgress(musicService.player.getCurrentPosition());
                }
                int duration2 = musicService.player.getDuration()/1000;//获取音乐总时长
                int position = musicService.player.getCurrentPosition()/1000;//获取当前播放的位置
                System.out.println(duration2+"--"+position);
                if(position>=duration2){
                    button_start.setEnabled(true);
                    button_start.setBackgroundColor(getResources().getColor(R.color.greenyellow));
                }
            }
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent intent = new Intent(this, MusicService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);
        initView();

    }

    private void initView() {
        textView = (TextView) findViewById(R.id.textView);
        button_start = (Button) findViewById(R.id.button_start);
        button_pause = (Button) findViewById(R.id.button_pause);
        button_stop = (Button) findViewById(R.id.button_stop);
        button_exit = (Button) findViewById(R.id.button_exit);

        button_start.setOnClickListener(this);
        button_pause.setOnClickListener(this);
        button_stop.setOnClickListener(this);
        button_exit.setOnClickListener(this);
        seekbar = (SeekBar) findViewById(R.id.seekbar);
        seekbar.setOnClickListener(this);
        seekbar = findViewById(R.id.seekbar);
        initSeekBar();//初始化进度条
        tv_start = (TextView) findViewById(R.id.tv_start);
        tv_start.setOnClickListener(this);
        tv_end = (TextView) findViewById(R.id.tv_end);
        tv_end.setOnClickListener(this);
    }

    //关于进度条初始化
    public void initSeekBar() {
        //初始化时绑定服务
        conn = new MyConn();
        intent = new Intent(MainActivity.this, MusicService.class);
        bindService(intent, conn, BIND_AUTO_CREATE);

        seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int duration2 = musicService.player.getDuration() / 1000;//获取音乐总时长
                int position = musicService.player.getCurrentPosition();//获取当前播放的位置
                tv_start.setText(calculateTime(position / 1000));//开始时间
                tv_end.setText(calculateTime(duration2));//总时长
            }

            /*
             * 通知用户已经开始一个触摸拖动手势。
             * */
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekbarChaning = true;
            }

            /*
             * 当手停止拖动进度条时执行该方法
             * 首先获取拖拽进度
             * 将进度对应设置给MediaPlayer
             * */
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekbarChaning = false;
                musicService.player.seekTo(seekBar.getProgress());//在当前位置播放
                tv_start.setText(calculateTime(musicService.player.getCurrentPosition() / 1000));
            }
        });
    }

    @Override
    public void onClick(View v) {
        button_start.setBackgroundColor(getResources().getColor(R.color.greenyellow));
        button_pause.setBackgroundColor(getResources().getColor(R.color.greenyellow));
        button_stop.setBackgroundColor(getResources().getColor(R.color.greenyellow));
        button_exit.setBackgroundColor(getResources().getColor(R.color.greenyellow));
        button_start.setEnabled(true);
        button_pause.setEnabled(true);
        button_stop.setEnabled(true);
        switch (v.getId()) {
            case R.id.button_start:
                button_start.setBackgroundColor(getResources().getColor(R.color.darkseagreen));
                musicService.play();
                button_start.setEnabled(false);
                //进度条
                initSeekBar();
                int duration = musicService.player.getDuration();//获取音乐总时间
                seekbar.setMax(duration);//将音乐总时间设置为Seekbar的最大值

                //method1
                /*timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (!isSeekbarChaning) {
                            seekbar.setProgress(musicService.player.getCurrentPosition());
                        }
                    }
                }, 0, 50);*/



                //method2
                Thread thread=new Thread(){
                    @Override
                    public void run() {
                        System.out.println("run");
                        int i;
                        for(i=1;;i++){
                            try{
                                Thread.sleep(1000);
                                //System.out.println("发送时间");
                            }catch (Exception e){
                            }
                            Message message=handler.obtainMessage();
                            message.arg1=i;
                            handler.sendMessage(message);
                        }
                        //super.run();
                    }
                };
                thread.start();
                break;
            case R.id.button_pause:
                button_pause.setBackgroundColor(getResources().getColor(R.color.darkseagreen));
                musicService.pause();
                button_pause.setEnabled(false);
                break;
            case R.id.button_stop:
                button_stop.setBackgroundColor(getResources().getColor(R.color.darkseagreen));
                musicService.stop();
                button_pause.setEnabled(false);
                button_stop.setEnabled(false);
                break;
            case R.id.button_exit:
                button_exit.setBackgroundColor(getResources().getColor(R.color.darkseagreen));
                musicService.stop();
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        MainActivity.this.removeDialog(R.id.seekbar);
        unbindService(conn);
    }

    //计算播放时间
    public String calculateTime(int time) {
        int minute;
        int second;
        if (time > 60) {
            minute = time / 60;
            second = time % 60;
            //分钟再0~9
            if (minute >= 0 && minute < 10) {
                //判断秒
                if (second >= 0 && second < 10) {
                    return "0" + minute + ":" + "0" + second;
                } else {
                    return "0" + minute + ":" + second;
                }
            } else {
                //分钟大于10再判断秒
                if (second >= 0 && second < 10) {
                    return minute + ":" + "0" + second;
                } else {
                    return minute + ":" + second;
                }
            }
        } else if (time < 60) {
            second = time;
            if (second >= 0 && second < 10) {
                return "00:" + "0" + second;
            } else {
                return "00:" + second;
            }
        }
        return null;
    }


    class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //获取 MusicBinder 的实例
            MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
            musicService = binder.getService();//返回一个 MusicService 对象
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }


}
